package com.seanLab.tool;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ttx on 25/09/2017.
 */
public class ImgFilter {

    private static final Map<DecodeHintType, ErrorCorrectionLevel> decodeMap=new HashMap<DecodeHintType, ErrorCorrectionLevel>();
    private static MultiFormatReader multiFormatReader = new MultiFormatReader();
    final static double ratio = 2.5;

    public static List<Integer> filtrateImages(List<String> imgURL){
        List<Integer> rs = new ArrayList<>();
        for(String url:imgURL){
            rs.add(filtrateImg(url));
        }
        return rs;
    }

    //过滤图片相关函数
    private static Integer filtrateImg(String imgURL) {
        //为了使得读入图片次数减少和调用独立，因此，qrimg使用了保存在全局的tmpBufferedImg
        File file = new File(imgURL);
        if(!imgExist(file)){
            return 1;
        }

        //判断该图片是否可读
        BufferedImageLuminanceSource tmpBufferedImg;
        try {
            tmpBufferedImg = new BufferedImageLuminanceSource(ImageIO.read(new FileInputStream(imgURL)));
        } catch (Exception e) {
            return 2;
        }

        if(!imgBalance(tmpBufferedImg)){
            return 3;
        }
        if(isQRImg(tmpBufferedImg)){
            return 4;
        }
        return 0;
    }

    private static Boolean imgExist(File tmpFile) {
        try {
            // System.out.println(tmpImgName);
            if (tmpFile.exists()) {
                return true;
            }
        } catch (Exception e) {

        }
        return false;
    }

    private static Boolean imgBalance(BufferedImageLuminanceSource tmpBufferedImg) {
        double width = tmpBufferedImg.getWidth();
        double height = tmpBufferedImg.getHeight();
        if(width > 0 && height >0 && width / height < ratio && height / width < ratio){
            return true;
        }
        return false;
    }

    private static Boolean isQRImg(BufferedImageLuminanceSource tmpBufferedImg) {

        try {
            multiFormatReader.decode(new BinaryBitmap(new HybridBinarizer(tmpBufferedImg)), decodeMap).getText();
            return true;
        }catch (NotFoundException e){
            return false;
        }catch (Exception e){
            return true;
        }
    }
}
